package com.tsing.cli.system.service.impl;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.tsing.cli.common.dto.CustomUserDetails;
import com.tsing.cli.system.entity.UserEntity;
import com.tsing.cli.system.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 自定义用户认证逻辑
 *
 * @author TheTsing
 */
@Service
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserEntity userEntity = new LambdaQueryChainWrapper<>(userMapper)
                .select(UserEntity::getId, UserEntity::getUsername, UserEntity::getPassword, UserEntity::getStatus)
                .eq(UserEntity::getUsername, username)
                .one();
        if (Objects.isNull(userEntity)) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        return new CustomUserDetails()
                .setId(userEntity.getId())
                .setUsername(userEntity.getUsername())
                .setPassword(userEntity.getPassword())
                .setPermissions(userMapper.getPerms(userEntity.getId()))
                .setEnabled(userEntity.getStatus());
    }

}
